package com.weakteam.mobile.minimum.service.task;

import com.weakteam.mobile.minimum.common.util.SimpleLog;
import com.weakteam.mobile.minimum.common.util.UrlBuilder;
import com.weakteam.mobile.minimum.data.CityData;
import com.weakteam.mobile.minimum.service.AsyncRequest;
import com.weakteam.mobile.minimum.service.ServerData;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Nail Sharipov (nailxsharipov@gmail.com) on 11.11.2014.
 */
public class GetCities extends AsyncRequest {

    private List<CityData> cities;

    public List<CityData> getCities() {
        return cities;
    }

    @Override
    protected Void doInBackground(Void... params) {
        final String baseURL = ServerData.getInstance().getBaseServerUrl();
        final URL url = new UrlBuilder().setServerURL(baseURL)
                .addParameter("t", "14")
                .addParameter("l", "javamobile")
                .addParameter("p", "ky7!7gAsqqK")
                .addParameter("lang", "ru")
                .getURL();

        try {
            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(false);
            connection.setConnectTimeout(CONNECTION_TIME_OUT);
            connection.setReadTimeout(CONNECTION_TIME_OUT);

            // get response
            int status = connection.getResponseCode();

            switch (status) {
                case HttpURLConnection.HTTP_OK:
                    final String response = this.readStream(connection);
                    this.cities = this.getCitiesFromText(response);
                    break;
                default:
                    SimpleLog.info("status code: " + status);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private CityData parseCity(String text) {
        Map<String, String> data = new HashMap();

        int n = text.length();

        char openBracket = '[';
        char closeBracket = ']';

        boolean isOpen = true;
        int start = 0;
        int end;

        for (int i = 0; i < n; i++) {
            char current = text.charAt(i);
            if (isOpen) {
                if (current == openBracket) {
                    start = i + 1;
                    isOpen = false;
                }
            } else if (current == closeBracket) {
                end = i;
                isOpen = true;

                String block = text.substring(start, end);
                if (block.length() > 2) {
                    String[] subStrings = block.split("=");
                    String parameter = subStrings[0];
                    String value = subStrings[1];
                    data.put(parameter, value);
                }
            }
        }

        final CityData city = new CityData(data);

        return city;
    }

    private List<CityData> getCitiesFromText(String text) {
        List<CityData> cities = new ArrayList();
        int n = text.length();

        char separator = '\n';
        int start = 0;
        int end;

        for (int i = 0; i < n; i++) {
            if (i == n - 1 || text.charAt(i) == separator) {
                end = i;
                final String block = text.substring(start, end + 1);
                start = end + 1;
                if (block.length() > 2) {
                    final CityData city = this.parseCity(block);
                    cities.add(city);
                }
            }
        }

        return cities;
    }

}